package com.zrc.japktool.apk.keytool;
import com.zrc.japktool.util.TaskLog;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.X509v3CertificateBuilder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;

import java.io.FileOutputStream;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import java.util.Date;

public class KeyTool {
    private TaskLog log = null;

    public KeyTool(TaskLog log) {
        this.log = log;
    }

    public void generateKeystore(String keystorePath, String alias, String storePassword, String keyPassword, int validityYears, String dname) throws Exception {
        log.info("1. 创建 KeyStore 实例 (PKCS12 格式)");

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(null, null); // 初始化空 keystore

        log.info("2. 设置有效期");
        Calendar calendar = Calendar.getInstance();
        Date startDate = calendar.getTime();
        calendar.add(Calendar.YEAR, validityYears);
        Date endDate = calendar.getTime();

        log.info("3. 生成 RSA 密钥对");
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048); // 2048-bit RSA
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        log.info("4. 创建自签名证书");
        X500Name x500Name = new X500Name(dname);
        BigInteger serialNumber = new BigInteger(64, new SecureRandom());
        X509Certificate cert = createSelfSignedCert(x500Name, serialNumber, startDate, endDate, keyPair, "SHA256withRSA");

        log.info("5. 将密钥和证书存入 KeyStore");
        Certificate[] certChain = {cert};
        keyStore.setKeyEntry(alias, keyPair.getPrivate(), keyPassword.toCharArray(), certChain);

        log.info("6. 保存到文件");
        try (FileOutputStream fos = new FileOutputStream(keystorePath)) {
            keyStore.store(fos, storePassword.toCharArray());
        }
    }

    // 使用 Bouncy Castle 创建自签名证书
    private X509Certificate createSelfSignedCert(X500Name issuer, BigInteger serialNumber, Date startDate, Date endDate, KeyPair keyPair, String signatureAlgorithm) throws Exception {
        // 使用相同的issuer和subject创建自签名证书
        X500Name subject = issuer;

        // 创建证书构建器
        X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(issuer, serialNumber, startDate, endDate, subject, keyPair.getPublic());

        // 创建签名器
        ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(keyPair.getPrivate());

        // 构建证书
        X509CertificateHolder certHolder = certBuilder.build(signer);

        // 转换为X509Certificate
        return new JcaX509CertificateConverter().getCertificate(certHolder);
    }

    // 示例用法
    public static void main(String[] args) {
//        try {
//            generateKeystore(
//                    "C:/Users/Administrator/Desktop/xapk/android.keystore",
//                    "myalias",
//                    "mystorepass",
//                    "mykeypass",
//                    365*100,
//                    "CN=Android Developer, OU=Mobile, O=Company, L=Beijing, ST=Beijing, C=CN",
//                    System.out::println);
//            System.out.println("Keystore generated successfully!");
//        } catch (Exception e) {
//            System.err.println("Keystore generation failed:");
//            e.printStackTrace();
//        }
    }
}